<template>
	<view class="content">
		<u--form :model="form" ref="uForm" :borderBottom="true" labelPosition="top" labelWidth="300">
			<u-form-item :borderBottom="true" label="卡号" prop="bank_card">
				<u-input border="none" v-model="form.bank_card" placeholder="请输入卡号" />
				<view slot="right" @click="selectImg2('bank_image')">
					<u-icon name="camera-fill" color="#c1c1c1" size="56"></u-icon>
				</view>
			</u-form-item>
			<u-form-item :borderBottom="true" label="开户行" prop="kaihu" @click="khh.typeShow = true">
				<u-input border="none" :readonly="true" v-model="form.kaihu" type="select" 
					placeholder="请输入开户行" />
			</u-form-item>
			<u-form-item :borderBottom="true" label="开户省市" prop="city1" @click="city.cityShow=true">
				<u-input border="none" :readonly="true" v-model="form.city1" type="select" 
					placeholder="请输入开户省市" />
			</u-form-item>
			<u-form-item :borderBottom="true" label="有效期" prop="valid_date" @click="timeChange">
				<u-input border="none" :readonly="true" v-model="form.valid_date" type="select" 
					placeholder="请输入有效期" />
			</u-form-item>
			<u-form-item :borderBottom="true" label="账单日" prop="statement_date" @click="statementChange">
				<u-input border="none" :readonly="true" v-model="form.statement_date" type="select" 
					placeholder="请输入账单日" />
			</u-form-item>
			<u-form-item :borderBottom="true" label="还款日" prop="repayment_date" @click="repaymentChange">
				<u-input border="none" :readonly="true" v-model="form.repayment_date" type="select" 
					placeholder="请输入还款日" />
			</u-form-item>
			<u-form-item :borderBottom="true" label="安全码" prop="cvv2">
				<u-input border="none" v-model="form.cvv2" placeholder="请输入安全码" />
			</u-form-item>
			<u-form-item :borderBottom="true" label="额度" prop="quota">
				<u-input border="none" v-model="form.quota" placeholder="请输入额度" />
			</u-form-item>
			<u-form-item :borderBottom="true" label="银行预留手机号" prop="mobile">
				<u-input border="none" v-model="form.mobile" placeholder="请输入手机号" />
			</u-form-item>

		</u--form>
		<view style="margin: 40rpx 0;">
			<u-button shape="circle" color="linear-gradient(to left, #e44e15, #f4aa56)" text='提交' @click="submit">
			</u-button>
		</view>
		<!-- 开户行 -->
		<u-picker :show="khh.typeShow" title="选择开户行" :singleIndex="khh.defaultIndex[0]" :closeOnClickOverlay="true" visibleItemCount="16"
			@cancel="playCancel" :columns="[khh.typeList]" @confirm="khhConfirm">
		</u-picker>
		<!-- 开户省市 -->
		<u-picker :show="city.cityShow" ref="cityPicker" :defaultIndex="city.defaultIndex" :closeOnClickOverlay="true" title="选择开户省市" :columns="city.provinceData"
			visibleItemCount="16" @change="cityChange" @confirm="cityConfirm" @cancel="playCancel">
		</u-picker>
		<!-- 有效期 -->
		<u-datetime-picker :show="timeShow" title="选择有效期" :minDate="minDate" :maxDate="maxDate" mode="year-month" visibleItemCount="16" :closeOnClickOverlay="true"
			@confirm="timeConfirm" @cancel="playCancel"> </u-datetime-picker>
		<!-- 账单日 -->
		<u-picker :show="statementShow" title="选择出账日" :closeOnClickOverlay="true" visibleItemCount="16"
					@cancel="playCancel" :columns="[statementDate]" @confirm="statementConfirm">
				</u-picker>
		<!-- <u-picker :show="statementShow" mode="time" :mask-close-able="false" :params="params"
			:default-time="form.statement_date" @confirm="statementConfirm" @cancel="playCancel"> </u-picker> -->
		<!-- 还款日 repayment_date-->
		<u-picker :show="repaymentShow" title="选择最后还款日" :closeOnClickOverlay="true" visibleItemCount="16"
			@cancel="playCancel" :columns="[statementDate]" @confirm="repaymentConfirm">
		</u-picker>

	</view>
</template>

<script>
	import {
		areaId,
	} from '../../common/http.api.js'
	
	import {banks,bankcardUpdate, bankcardAdd} from '../../common/bankcard.api.js'
	
	export default {
		data() {
			return {
				deCode: '',
				globalData: [],
				timeShow: false,
				timeDefaultIndex: [0],
				statementShow: false,
				statementDate: [],
				statementDefaultIndex: [0],
				repaymentShow: false,
				repaymentDefaultIndex: [0],
				minDate: '',
				maxDate: '',
				pickerStartYear: 2022,
				pickerDefaultTime: '',
				params: {
					year: false,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				form: {
					bank_card: '',
					kaihu: '',
					bank_id: '',
					city1: '',
					province: '',
					valid_date: '',
					statement_date: '',
					repayment_date: '',
					cvv2: '',
					quota: '',
					mobile: '',
					type: '02'
				},
				city: {
					cityShow: false,
					cityInfo: "请选择",
					provinceData: [],
					cityData: [],
					defaultIndex: [0, 0]
				},
				kaihuList: [],
				khh: {
					typeShow: false,
					typeList: [],
					typeName: '',
					typeVlaue: [0],
					defaultIndex: [0]
				},
				rules: {
					bank_card: [{
						type: 'number',
						required: true,
						message: '请输入正确的银行卡号',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change', 'blur'],
					}],
					kaihu: [{
						required: true,
						message: '请选择开户行',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change', 'blur'],
					}],
					city1: [{
						required: true,
						message: '请选择开户省市',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change', 'blur'],
					}],
					valid_date: [{
						required: true,
						message: '请选择有效期',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change'],
					}],
					statement_date: [{
						required: true,
						message: '请选择账单日',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change', 'blur'],
					}],
					repayment_date: [{
						required: true,
						message: '请选择还款日',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change', 'blur'],
					}],
					cvv2: [{
						required: true,
						message: '请输入安全码',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change', 'blur'],
					}],
					quota: [{
						type: 'number',
						required: true,
						message: '请输入额度',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change'],
					}],
					mobile: [{
						type: 'number',
						required: true,
						message: '请输入正确手机号',
						// 可以单个或者同时写两个触发验证方式 
						// trigger: ['change'],
					}],
				},
				areaList: [],
				source:null
			};
		},
		onShow() {
			this.globalData = getApp().globalData
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(option) {
			console.log(option.deCode)
			if (JSON.stringify(option) != "{}" && option.deCode) {
				uni.setNavigationBarTitle({
					title: '编辑信用卡'
				})
				let deCode = JSON.parse(option.deCode);
				this.deCode = JSON.parse(option.deCode)
				
				console.log(deCode)
				
				this.form.bank_card = deCode.full_card_number;
				this.khh.typeVlaue = []
				this.khh.typeVlaue.push(deCode.banks_id);
				this.form.kaihu = deCode.name
				this.form.valid_date = deCode.valid_date;
				if (deCode.repayment_date * 1 < 10) {
					deCode.repayment_date = '0' + deCode.repayment_date
				}
				this.form.repayment_date = deCode.repayment_date.toString();
				if (deCode.statement_date * 1 < 10) {
					deCode.statement_date = '0' + deCode.statement_date
				}
				this.form.statement_date = deCode.statement_date.toString();
				this.form.cvv2 = deCode.cvv2;
				this.form.quota = deCode.quota
				this.form.mobile = deCode.mobile
				this.form.province = deCode.province
				this.form.city = deCode.city
				this.form.bank_id = deCode.banks_id
			}
			this.source = option.source
			this.getAreaList()
			this.getBanks()

			let date = new Date();
			this.minDate = date.getTime() 
			this.maxDate = date.getTime() + 100 * 365 * 24 * 60 * 60 * 1000
			
			for(let i = 1; i<= 31; i++){
				let date = i;
				if(date < 10){
					date = '0' + date
				}
				this.statementDate.push(date)
			}

		},
		methods: {
			showPicker(name){
				uni.hideKeyboard()
				this.khh.typeShow = true
			},
			selectImg2(e) {
				let _self = this;
				let token = uni.getStorageSync('token')
				uni.chooseImage({
					count: 1, //默认9
					type: 'image', //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						uni.showLoading({
							title: '加载中'
						})
						uni.uploadFile({
							url: _self.globalData.APP_API_BASE_URI + '/api/user/ocr/bank',
							filePath: res.tempFilePaths[0],
							name: 'bank_image',
							formData: {
								'token': token,
							},
							header: {
								"Content-Type": "multipart/form-data",
								"token": token
							},
							success: (uploadFileRes) => {
								let data = JSON.parse(uploadFileRes.data);
								uni.hideLoading()
								if (data.status == "failed") {
									uni.showToast({
										title: data.failedMsg,
										icon: 'none'
									})
								} else {
									_self.form.bank_card = data.data.bank_card_number
			
								}
							},
							fail: (e) => {
			
							}
						});
					}
				});
			},
			// 获取银行列表banks
			getBanks() {
				uni.showLoading({
					title: '加载中'
				})
				banks().then(res => {
					uni.hideLoading()
					for(let i = 0; i < res.length; i++){
						this.khh.typeList.push(res[i].name)
						
						//xiugai 
						if(this.deCode){
							if(this.form.kaihu == res[i].name){
								this.khh.defaultIndex = [i]
							}
						}
					}
					this.kaihuList = res
				})
			},
			getAreaList() {
				uni.showLoading({
					title: '加载中'
				})
				areaId().then(res => {
					uni.hideLoading()
					this.areaList = res;
					let tmpCity = []
					let tmpProvince = []
					let defaultCity = 0
					for (let i = 0; i < this.areaList.length; i++) {
						tmpProvince.push(this.areaList[i].name)
						for (let j = 0; j < this.areaList[i].city.length; j++) {
							tmpCity.push(this.areaList[i].city[j].name)
							
							//xiugai 
							if(this.deCode){
								if(this.form.province == this.areaList[i].id && this.form.city == this.areaList[i].city[j].id){
									this.city.defaultIndex = [i, j]
									this.form.city1 = this.areaList[i].name + ' ' + this.areaList[i].city[j].name
									defaultCity = i
								}
							}
						}
						this.city.cityData.push(tmpCity)
						tmpCity = []
					}
				
					this.city.provinceData.push(tmpProvince)
					this.city.provinceData.push(this.city.cityData[defaultCity])
				})
			},
			// 开户行选择
			khhConfirm(e) {
				this.khh.typeShow = false;
				this.form.kaihu = this.khh.typeList[e.indexs[0]]
				this.form.bank_id = this.kaihuList[e.indexs[0]].id
				this.khh.typeVlaue = [e.indexs[0]]
			},

			cityChange(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.cityPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.city.cityData[index])
				}
			},

			// 开户省市选择
			cityConfirm(e) {
				this.form.city = this.areaList[e.indexs[0]].city[e.indexs[1]].id
				this.form.province = this.areaList[e.indexs[0]].id
				this.form.city1 = this.areaList[e.indexs[0]].name + ' ' + this.areaList[e.indexs[0]].city[e.indexs[1]].name
				
				this.city.cityShow = false;
			},
			// 有效期选择
			timeConfirm(e) {
				console.log(e)
				let date = new Date(e.value);
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				this.timeShow = false;
				
				if (month < 10) {
					month = '0' + month
				}

				if (year) {
					year = year.toString().slice(-2)
				}
				this.form.valid_date = month + '/' + year
			},
			timeChange() {
				this.timeShow = true;
			},
			// 账单日修改
			statementChange() {
				this.statementShow = true
			},
			statementConfirm(e) {
				this.statementShow = false
				this.form.statement_date = e.value[0]
			},
			// 还款日repayment_date
			repaymentChange() {
				this.repaymentShow = true
			},
			repaymentConfirm(e) {
				this.repaymentShow = false
				this.form.repayment_date = e.value[0]
			},
			playCancel() {
				this.repaymentShow = false;
				this.timeShow = false;
				this.statementShow = false;
				this.city.cityShow = false;
				this.khh.typeShow = false;
			},
			submit() {
				let params = this.form;
				uni.showLoading({
					title: '提交中...'
				})
				this.$refs.uForm.validate().then(res => {
					if (this.deCode) {
						params.id = this.deCode.id;
						bankcardUpdate(params).then(res => {
							uni.hideLoading()
							uni.$emit('updateBankCardInfo',{type:'02'})
							uni.$u.toast('修改成功')
						})
					} else {
						bankcardAdd(params).then(res => {
							uni.hideLoading()
							uni.$emit('updateBankCardInfo',{type:'02'})
							uni.$u.toast('添加成功')
							if(this.source == 'repayment'){
								uni.$u.route({
									url: 'pages/repayment/index'
								})
							}else{
								uni.$u.route({
									url: 'pages/bankcard/index'
								})
							}
							
						})
					}
					
				}).catch(errors => {
					uni.hideLoading()
					uni.$u.toast('请检查填写内容')
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.content {
		padding: 0 30rpx;
		padding-bottom: 50rpx;
	}
</style>
